package org.elanfox.cloud.redis;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author allan
 * @date 2019-06-23
 */
public class RedisTemplate extends org.springframework.data.redis.core.RedisTemplate<String, Object> {
    private static final Integer DEFAULT_EXPIRE = 12;

    @SuppressWarnings("unchecked")
    public <T> T get(String key) {
        return (T) opsForValue().get(key);
    }

    public int getInt(String key) {
        Object obj = opsForValue().get(key);
        if (obj == null) {
            return 0;
        }
        return (int) obj;
    }

    public long getLong(String key) {
        Object object = this.opsForValue().get(key);
        if (object != null) {
            return (int) object;
        }
        return 0L;
    }

    public BigDecimal getBigDecimal(String key, int scale) {
        Object object = opsForValue().get(key);
        if (object != null) {
            double value = Double.parseDouble(object.toString());
            return BigDecimal.valueOf(value).setScale(scale, BigDecimal.ROUND_HALF_UP);
        }

        return BigDecimal.ZERO;
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> listAll(String key) {
        List<T> list = (List<T>) opsForList().range(key, 0, -1);
        if (list == null) {
            return new ArrayList<>();
        }
        return list;
    }

    public long listSize(String key) {
        Long size = opsForList().size(key);
        return size == null ? 0L : size;
    }

    /**
     * 分组获取列表
     *
     * @param key
     * @param pageIndex index from 1
     * @param pageSize
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> listAll(String key, int pageIndex, int pageSize) {
        int start = (pageIndex - 1) * pageSize;
        int end = start + pageSize - 1;

        return (List<T>) opsForList().range(key, start, end);
    }
}
